package com.zn.opit.shirodemo.config.shiro;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.crazycake.shiro.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

public class MyRedisSerializer<T> implements RedisSerializer<T> {

    static {
        // 此配置不加会报类型转换异常
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);//开启AutoType
        ParserConfig.getGlobalInstance().addAccept("com.zn");//二、设置白名单
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        try {
            return JSON.toJSONBytes(t, SerializerFeature.WriteClassName);
        } catch (Exception ex) {
            throw new SerializationException("Could not write JSON: " + ex.getMessage(), ex);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null) return null;
        String data = new String(bytes);
        return (T) JSON.parse(data);
    }
}
